﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Htse.Blue.Logic.Validation;
using Htse.Blue.Logic;
using Htse.Blue.Models;
using System.Linq.Dynamic;
using System.Data.Linq;
using Htse.Blue.Models.ViewModels;

namespace Htse.Blue.Controllers
{
	[HandleError(Order=0)]
	public class CarController : Controller
	{
		private ICarService _carService;

		public CarController()
		{
			_carService = new CarService(new ModelStateWrapper<Car>(ModelState));
		}

		public CarController(ICarService carService)
		{
			_carService = carService;
		}

		[Authorize]
		public ActionResult ListForUmpire(Umpire umpire, int? page, string sort)
		{
			var cars = _carService.ListForUmpire(umpire.Id, page, SiteConstants.PAGE_SIZE, sort);

			return PartialView("DisplayCars", new CarDisplayViewModel(cars, umpire));
		}

		[Authorize]
		public ActionResult Create(int umpireId)
		{
			Car car = new Car() { UmpireId = umpireId };

			return View("Create", car);
		}

		[Authorize]
		[ValidateAntiForgeryToken]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Create([Bind(Exclude = "Id")] Car car)
		{
			bool result = _carService.Create(car);

			if (result)
			{
				return RedirectToAction("Display", "Umpire");
			}
			else
			{
				return View("Create", car);
			}
		}

		[Authorize]
		public ActionResult Edit(int id)
		{
			Car car = _carService.GetById(id);

			if (car == null)
			{
				return View("NotFound");
			}

			if (!ControllersHelper.IsCurrentUmpireTheCurrentUser(car.Umpire, User))
			{
				return View("NotAllowed");
			}

			return View("Edit", car);
		}

		[Authorize]
		[AcceptVerbs(HttpVerbs.Post)]
		[ValidateAntiForgeryToken]
		[HandleError(ExceptionType = typeof(ChangeConflictException), View = "ConcurrencyError")]
		public ActionResult Edit(Car car)
		{
			bool result = _carService.Update(car);

			if (result)
			{
				return RedirectToAction("Display", "Umpire");
			}
			else
			{
				return View("Edit", car);
			}
		}

		[Authorize]
		[AcceptVerbs(HttpVerbs.Delete)]
		[ActionName("Delete")]
		public ActionResult AjaxDelete(int id)
		{
			var carToDelete = _carService.GetById(id);

			if (carToDelete == null)
			{
				return View("NotFound");
			}

			if (!ControllersHelper.IsCurrentUmpireTheCurrentUser(carToDelete.Umpire, User))
			{
				return View("NotAllowed");
			}

			_carService.Delete(carToDelete);

			return RedirectToAction("Display", "Umpire");
		}
	}
}
